from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import time

class Grap():
    def __init__(self):
        #设置驱动路径，selenium4之后的新写法
        self.service = Service(executable_path=r"C:\Program Files\Google\Chrome\Application\chromedriver.exe")
        # 实例化浏览器对象
        self.driver = webdriver.Chrome(service=self.service) 
    
    def test(self):
        self.driver.get("https://www.baidu.com")
        self.driver.get("https://www.taobao.com")
        self.driver.back()           #返回百度
        self.driver.forward()        #进入淘宝
        self.driver.refresh()
        print("当前页面的标题: {}".format(self.driver.title))
        print("当前页面的url: {}".format(self.driver.current_url))
        self.driver.save_screenshot("taobao.png")
        self.driver.close()
        self.driver.quit()
    #通过id属性定位元素
    def find_id(self):
        self.driver.get("https://news.baidu.com/")
        #element = self.driver.find_element_by_id("header-wrapper")
        element = self.driver.find_element(By.ID,"header-wrapper")
        print(element.text)
    #通过class属性来定位元素
    def find_class(self):
        self.driver.get("https://news.baidu.com/")
        element = self.driver.find_element(By.CLASS_NAME,"mod-headline-tab")
        print(element.text)
    #单击鼠标左键
    def click_mouse_test(self):
        self.driver.get("https://www.baidu.com")
        self.driver.maximize_window()
        element = self.driver.find_element(By.ID,"s-top-loginbtn")
        time.sleep(2)
        ActionChains(self.driver).click(on_element=element).perform()
        time.sleep(3)
    #鼠标悬停
    def move_to_test(self):
        self.driver.get("https://www.baidu.com")
        self.driver.maximize_window()
        element = self.driver.find_element(By.XPATH,'//*[@id="s-usersetting-top"]')
        ActionChains(self.driver).move_to_element(element).perform()
        time.sleep(5)
        element1 = self.driver.find_element(By.XPATH,"//div/a[@class='setpref first']")
        element1.click()
        time.sleep(5)
    #鼠标拖动
    def drag_and_drop_test(self):
        self.driver.get("https://portal.fuyunfeng.top/plugins_v2/index.html#/slider-verify-example")
        element = self.driver.find_element(By.ID,"circle")
        action=ActionChains(self.driver)
        action.click_and_hold(element)
        action.drag_and_drop_by_offset(element,100,0)#向右拖拽100个像素
        time.sleep(2)
        action.perform()

if __name__=="__main__":
    g = Grap()
    g.drag_and_drop_test()